package com.java123.t10.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * net包，常见两种协议：tcp、udp。
 *
 */
public class Server {

	public static void main(String[] args) {
		//tcpServer();
		udpServer();
	}

	/**
	 * tcp服务端
	 */
	public static void tcpServer() {
		try {
			// 绑定端口
			ServerSocket server = new ServerSocket(9999);
			System.out.println("正在监听tcp服务....");

			// 等待客户端连接 ，线程阻塞
			Socket socket = server.accept();

			// 获得输入流
			InputStream input = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(input));

			StringBuffer sb = new StringBuffer();
			String info = null;

			// 读取数据
			while ((info = br.readLine()) != null) {
				sb.append(info);
			}
			System.out.println("tcp->客户端数据：" + sb.toString());

			// 关闭输入流
			socket.shutdownInput();

			// 响应客户端
			// 获取输出流
			OutputStream output = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(output);
			pw.write("数据已收到！");
			pw.flush();
			
			// 关闭输出流
			socket.shutdownOutput();

			// 释放资源
			br.close();
			input.close();
			socket.close();
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * udp服务端
	 */
	public static void udpServer() {
		try {
			// 绑定端口
			DatagramSocket server = new DatagramSocket(9998);
			System.out.println("正在监听udp服务....");

			// 建立字节数组来接收udp包
			byte[] buf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf, 1024);
			server.receive(packet);

			// 读取数据
			String info = new String(packet.getData(), 0, packet.getLength());
			System.out.println("接收到客户端数据：" + info);

			/**
			 * 响应客户端
			 */
			InetAddress address = packet.getAddress();
			int port = packet.getPort();
			byte[] buf2 = "已收到!".getBytes();
			// 创建响应的数据报
			DatagramPacket packet2 = new DatagramPacket(buf2, buf2.length, address, port);
			// 响应客户端
			server.send(packet2);

			// 释放资源
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
